package com.zenithmind.gateway.logging;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

/**
 * 默认网关日志记录器实现
 * 专门负责网关请求的日志记录
 * 遵循单一职责原则：只负责日志记录逻辑
 */
@Slf4j
@Component
public class DefaultGatewayLogger implements GatewayLogger {

    @Override
    public void logRequestStart(ServerHttpRequest request, String targetService, String userId) {
        String requestPath = request.getURI().getPath();
        String requestMethod = request.getMethod().name();
        String remoteAddress = request.getRemoteAddress() != null ? 
            request.getRemoteAddress().getHostString() : "unknown";

        log.info("收到请求 [{}] {} 来自 {}, 目标服务: {}, 用户: {}",
                requestMethod, requestPath, remoteAddress, targetService,
                userId != null ? userId : "匿名");
    }

    @Override
    public void logRequestComplete(ServerWebExchange exchange, String targetService, String userId, long executionTime) {
        ServerHttpRequest request = exchange.getRequest();
        String requestPath = request.getURI().getPath();
        String requestMethod = request.getMethod().name();

        // 获取响应状态码
        int statusCode = exchange.getResponse().getStatusCode() != null ?
                exchange.getResponse().getStatusCode().value() : 200;

        log.info("完成请求 [{}] {} 状态码: {} 耗时: {}ms 用户: {} 目标服务: {}",
                requestMethod, requestPath, statusCode, executionTime,
                userId != null ? userId : "匿名", targetService);
    }

    @Override
    public void logRequestError(ServerWebExchange exchange, String targetService, String userId, long executionTime, Throwable throwable) {
        ServerHttpRequest request = exchange.getRequest();
        String requestPath = request.getURI().getPath();
        String requestMethod = request.getMethod().name();

        log.error("请求错误 [{}] {} 错误: {} 耗时: {}ms 用户: {} 目标服务: {}",
                requestMethod, requestPath, throwable.getMessage(), executionTime,
                userId != null ? userId : "匿名", targetService);
    }

    @Override
    public void logRequestParameters(ServerHttpRequest request) {
        if (request.getQueryParams() != null && !request.getQueryParams().isEmpty()) {
            log.debug("请求参数: {}", request.getQueryParams());
        }
    }
}
